import Vue from 'vue'
import Router from 'vue-router'

import Admin from './Admin'
import Auth from './Auth'
import Custom from './Custom'
import Market from './Market'

import Error404 from '@/components/Error404'
import Experiment from '@/components/Experiment'

import { checkAuth } from '@/utils/checkAuth'
import VueApp from '@/main'

Vue.use(Router)

const router = new Router({
  mode: 'history',
  base: 'app',
  routes: [
    {
      path: '/',
      redirect: {
        name: 'MarketList'
      }
    },
    Admin,
    Auth,
    Custom,
    Market,
    {
      path: '/exp',
      name: 'Experiment',
      component: Experiment,
      meta: { login: true, admin: false }
    },
    {
      path: '*',
      name: 'Error404',
      component: Error404
    }
  ]
})

router.beforeEach((to, from, next) => {
  let login = to.matched.some(record => record.meta.login)
  let admin = to.matched.some(record => record.meta.admin)
  if (login) {
    checkAuth().then(auth => {
      console.info('checkAuth hook -- ', auth)
      if (auth && auth.id) {
        if ((!admin) || (admin && auth.admin)) {
          next()
        } else {
          Vue.$notify.error({
            title: '需要管理员权限'
          })
          next({
            name: 'MarketList'
          })
        }
      } else {
        VueApp.$notify.warning({
          title: '请先登录'
        })
        next({
          path: '/auth/login',
          query: { redirect: to.fullPath }
        })
      }
    })
  } else {
    next() // 确保一定要调用 next()
  }
})

export default router
